<template>
  <!-- 属性 -->
  <div class="node-attr" :class="{ 'hidden-node-attr': isHidden }">
    <!-- 隐藏/显示 -->
    <div class="node-switch" @click="changeHidden">
      <el-icon>
        <DArrowLeft v-if="isHidden" />
        <DArrowRight v-else />
      </el-icon>
    </div>
    <!-- 看板 -->
    <div class="node-content">
      <el-collapse v-model="infoActive" accordion>
        <!-- 全局看板 -->
        <el-collapse-item
          v-if="graphData.canvasRoom === 'detail'"
          title="全局属性"
          name="1"
        >
          <div style="font-weight: 600; white-space: break-spaces">
            {{ node_label || '暂无' }}
          </div>
        </el-collapse-item>
        <!-- 节点看板 -->
        <el-collapse-item title="节点属性" name="2">
          <div v-if="isUser" class="na-item" id="seats-info-name-cascader">
            <span>姓名：</span>
            <el-cascader
              :disabled="isDisabled"
              placement="left"
              v-model.trim="graphData.editForm.user_id"
              :options="userList"
              filterable
              clearable
              :show-all-levels="true"
              style="width: 100%"
              @change="handleChange"
            />
          </div>
          <div v-if="isUser" class="na-item">
            <span>部门：</span>
            <el-input
              disabled
              type="textarea"
              rows="5"
              resize="none"
              :model-value="graphData.editForm.user_dept"
              @blur="save"
            />
          </div>
          <div v-if="isUser" class="na-item">
            <span>职位：</span>
            <el-input
              :disabled="isDisabled"
              v-model.trim="graphData.editForm.user_position"
              @blur="save"
            />
          </div>
          <div v-if="isUser" class="na-item">
            <span>职能：</span>
            <el-input
              :disabled="isDisabled"
              v-model.trim="graphData.editForm.user_role"
              @blur="save"
            />
          </div>
          <div v-if="isUser" class="na-item">
            <span>电话：</span>
            <el-input
              :disabled="isDisabled"
              v-model="graphData.editForm.user_phone"
              @blur="save"
            />
          </div>
          <div v-if="isRoom || isDesk || isCircle || isDoor" class="na-item">
            <span>文本：</span>
            <el-input
              :disabled="isDisabled"
              type="textarea"
              rows="5"
              resize="none"
              v-model="graphData.editForm.node_label"
              @blur="save"
            />
          </div>
          <div v-if="!isNone && !isCircle && !isDisabled" class="na-item">
            <span>宽度：</span>
            <el-input-number
              :min="1"
              :controls="false"
              :disabled="isDisabled"
              step-strictly
              v-model="graphData.editForm.node_width"
              @blur="save"
            />
          </div>
          <div v-if="!isNone && !isCircle && !isDisabled" class="na-item">
            <span>高度：</span>
            <el-input-number
              :min="1"
              :controls="false"
              :disabled="isDisabled"
              step-strictly
              v-model="graphData.editForm.node_height"
              @blur="save"
            />
          </div>
          <div v-if="!isNone && isCircle && !isDisabled" class="na-item">
            <span>半径：</span>
            <el-input-number
              :min="1"
              :controls="false"
              :disabled="isDisabled"
              step-strictly
              v-model="graphData.editForm.node_size"
              @blur="save"
            />
          </div>
          <div
            v-if="!isNone && graphData.canvasRoom === 'index' && !isDisabled"
            class="na-item"
          >
            <!-- 是否可以点击该组件跳转 -->
            <span>跳转：</span>
            <el-radio-group
              style="width: 100%"
              v-model="graphData.editForm.is_link"
              :disabled="isDisabled"
              @change="save"
            >
              <el-radio :label="true" size="large">可跳转</el-radio>
              <el-radio :label="false" size="large">不可跳转</el-radio>
            </el-radio-group>
          </div>
          <div v-if="isNone" class="none-node">暂无选中节点</div>
        </el-collapse-item>
      </el-collapse>
      <div v-if="hasEditRole" class="na-btn-box">
        <el-button
          class="na-btn"
          :type="graphData.onlyRead ? 'primary' : 'warning'"
          @click="changeModel(graphData)"
        >
          切换为{{ graphData.onlyRead ? '编辑模式' : '浏览模式' }}
        </el-button>
        <el-button
          v-if="!isDisabled"
          class="na-btn na-btn-width"
          type="primary"
          :loading="loading"
          @click="submit"
          auto-insert-space
        >
          提交
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ATTR_NODE } from '../node';
import {
  saveNode,
  changeModel,
  saveCanvas,
  initSize,
  initEditForm,
  deepUserList
} from '../common';
import { ElMessageBox } from 'element-plus';
import auth from '@/plugins/auth';
const props = defineProps({
  graphData: {
    type: Object,
    default: () => {}
  },
  userList: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
});
const emits = defineEmits();
const route = useRoute();
defineExpose({ changeInfoActive });

const isHidden = ref(false);
function changeHidden() {
  isHidden.value = !isHidden.value;
  setTimeout(() => {
    initSize(props.graphData, true);
  }, 500);
}

const hasEditRole = ref(auth.hasPermi('seatSystem:operator:edit'));
const node_label = ref('');
node_label.value = route.query?.node_label || '';
watch(route, val => {
  if (val.name !== 'CustomSeatsDetail') return;
  node_label.value = route.query?.node_label || '';
});

const infoActive = ref('1');
function changeInfoActive(val) {
  infoActive.value = val;
}

// 是否只读
const isDisabled = computed(() => props.graphData.onlyRead);

// 当前节点类型
const activenode_type = computed(() => {
  const _activeNode = props.graphData.activeNode;
  if (!_activeNode) return '';
  const _model = _activeNode.getModel();
  return _model.node_type;
});
const isNone = computed(() => !activenode_type.value);
const isUser = computed(() => activenode_type.value === 'user');
const isRoom = computed(() => activenode_type.value === 'room');
const isDesk = computed(() => activenode_type.value === 'desk');
const isDoor = computed(() => activenode_type.value === 'door');
const isCircle = computed(() => activenode_type.value === 'circle');

// 编辑节点
function save() {
  const _activeNode = props.graphData.activeNode;
  if (!_activeNode) return;
  const _editForm = props.graphData.editForm;
  let activeModel = JSON.parse(JSON.stringify(_activeNode.getModel()));
  activeModel = { ...activeModel, custom_info: _editForm };
  // 无员工
  const noneUserModel = {
    ...activeModel,
    ...ATTR_NODE.ATTR_USER_NONE,
    custom_info: _editForm
  };
  // 有员工
  const someUserModel = {
    ...activeModel,
    ...ATTR_NODE.ATTR_USER_SOME,
    custom_info: _editForm
  };
  if (activeModel.node_type === 'user') {
    if (_editForm?.user_id) {
      activeModel = someUserModel;
      deleteUser();
    } else activeModel = noneUserModel;
  }
  saveNode({ addModel: activeModel }, props.graphData);
}

// 删除已有该座位的员工
function deleteUser() {
  const _editForm = props.graphData.editForm || {};
  const _activeNode = props.graphData.activeNode || {};
  const canvasData = JSON.parse(saveCanvas(props.graphData));
  canvasData.nodes?.forEach(node => {
    const _custom_info = node.custom_info;
    if (
      _custom_info?.user_id === _editForm.user_id &&
      node.id != _activeNode._cfg?.id
    ) {
      initEditForm(_custom_info);

      saveNode(
        {
          addModel: {
            ...ATTR_NODE.ATTR_USER_NONE,
            x: node.x,
            y: node.y,
            custom_info: _custom_info
          },
          node: node,
          isDelete: true
        },
        props.graphData
      );
    }
  });
}

// 选择员工
function handleChange(valueList) {
  valueList = valueList || [];
  const userMap = {};
  deepUserList(props.userList, userMap);

  const userDeepList = [];
  getUser(props.userList, valueList, userDeepList);

  const userInfo = userMap[valueList[valueList.length - 1]] || {};
  const _editForm = props.graphData.editForm;
  initEditForm(_editForm);
  if (userInfo.value) {
    _editForm.user_id = userInfo.value || 0;
    _editForm.user_name = userInfo.label || '';
    _editForm.user_dept = userInfo.dept || '';
    _editForm.user_show_dept = userDeepList
      ?.slice?.(0, userDeepList.length - 1)
      ?.map(item => item.label)
      ?.join('-');
  }
  save();
  initInputValue();
}

watch(() => props.graphData.activeNode, initInputValue, { immediate: true });
// 重置级联input内容
async function initInputValue() {
  await nextTick();
  const inputDom = document.querySelector('#seats-info-name-cascader input');
  if (!inputDom) return;
  const _activeNode = props.graphData.activeNode || {};
  const _custom_info = _activeNode?.getModel?.()?.custom_info || {};
  inputDom.value = _custom_info.user_name || '';
}

// 通过id拿到用户信息
function getUser(list, valueList, userDeepList) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (item.value === valueList[userDeepList.length]) {
      userDeepList.push(item);
      if (item.children?.length) {
        getUser(item.children, valueList, userDeepList);
      }
      return;
    }
  }
}

// 提交
function submit() {
  ElMessageBox.confirm('确定提交当前画布？', '提示', {
    type: 'warning'
  })
    .then(() => {
      emits('submit');
    })
    .catch(() => {});
}
</script>

<style lang="scss" scoped>
.node-attr {
  line-height: 30px;
  margin-left: 0;
  width: 360px;
  margin-right: 15px;
  position: relative;
  transition: all 0.5s;
  overflow: hidden;
  .node-content {
    position: absolute;
    left: 24px;
    width: 336px;
  }
  :deep(.el-collapse) {
    padding: 0;
    border: none;
  }
  :deep(.el-collapse-item__header) {
    background-color: var(--el-color-primary-light-5);
    color: #008080;
    font-weight: 800;
    padding: 0 10px;
  }
  :deep(.el-collapse-item__content) {
    padding: 10px;
  }
}
.hidden-node-attr {
  width: 14px;
}
.na-btn-box {
  display: flex;
  justify-content: space-between;
}
.na-btn {
  margin-top: 10px;
}
.na-btn-width {
  width: 150px;
}
.none-node {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #aaa;
}
.na-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
  &:first-child {
    margin-top: 0;
  }
  &:last-child {
    margin-bottom: 0;
  }
  > span {
    width: 50px;
    text-align: right;
  }
  :deep(.el-input-number) {
    width: 100%;
    input {
      text-align: left;
    }
    .el-input__wrapper {
      padding: 1px 11px;
    }
  }
  :deep(.el-radio-group) {
    height: 24px;
    .el-radio {
      height: 100%;
    }
  }
}

.node-switch {
  width: 14px;
  background-color: #e5f2f2;
  border: 1px solid #7fbfbf;
  height: 100%;
  position: absolute;
  left: 0;
  cursor: pointer;
  box-sizing: border-box;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #008080;
  transition: all 0.2s;
  &:hover {
    background-color: #008080;
    color: #fff;
  }
}
</style>
